package com.zhiyou100.dao;

import com.zhiyou100.entity.Exam;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
@Repository
public class ExamDaoImp   implements   ExamDao{
    public List<Exam> getAllByEnameOrEtime(String ename, Date etime){
        return getSession().createQuery("from com.zhiyou100.entity.Exam  where ename=:en or etime=:et")
                .setString("en",ename).setDate("et",etime).list();
    }
    //分页查询
    public List<Exam> getAllFenYe(int startIndex,int pageSize){
        Query query=getSession().createQuery("from com.zhiyou100.entity.Exam order by etime desc");
        query.setMaxResults(pageSize);
        query.setFirstResult(startIndex);
        return query.list();
    }
    @Autowired
    private SessionFactory factory;
    private Session getSession(){
        return factory.openSession();
    }
    @Override
    public void addOne(Exam o) {//加上事务
        Session session=getSession();
        session.beginTransaction();
        session.save(o);   System.out.println("添加"+o);
        session.getTransaction().commit();;
    }

    @Override
    public void deleteOne(Integer integer) {//加上事务
           Session session=getSession();
           session.beginTransaction();
           Exam  e=session.get(Exam.class,integer);
           session.delete(e);System.out.println("删除"+e);
           session.getTransaction().commit();
    }
    @Override
    public void updateOne(Exam e) {//加上事务
        Session session=getSession();
        session.beginTransaction();
        session.update(e); System.out.println("修改"+e);
        session.getTransaction().commit();
    }
    @Override
    public List<Exam> getAll() {
          return getSession().createQuery("from com.zhiyou100.entity.Exam").list();
    }
    @Override
    public Exam getOne(Integer integer) {
        return getSession().get(Exam.class,integer);
    }
    @Override
    public Exam getOneByEname(String en) {
        return (Exam) getSession().createQuery("from com.zhiyou100.entity.Exam  where ename=:en").setString("en",en).uniqueResult();
    }
    @Override
    public Exam getOneByEtime(Date et) {
        return (Exam) getSession().createQuery("from com.zhiyou100.entity.Exam  where etime=:et").setDate("et",et).uniqueResult();
    }

}
